package com.dduggs.note.util;

import java.io.*;

/**
 * Created by CJS on 2017/4/11.
 * 拆分读取文件
 */
public class SpiltFileContentUtil {

    public static void ReadData(String sourceFile, int genFileNum) {
        try {
            File readFile = new File(sourceFile);
            FileReader read = new FileReader(readFile);
            BufferedReader br = new BufferedReader(read);
            String row;
            //行号标识
            int rownum = 1;
            //文件标识
            int fileNo = 1;
            int totalNum = getTotalLines(sourceFile);
            if(totalNum==0){
                System.out.println("文件为空");
                return;
            }
            String filename = "0" + fileNo + ".txt";
            File outputFile = new File("D:/ztest/" + filename);
            FileWriter fileWriter = new FileWriter(outputFile);

            while ((row = br.readLine()) != null) {

                if (rownum > totalNum / genFileNum * fileNo) {
                    fileWriter.close();
                    ++fileNo;
                    filename = "0" + fileNo + ".txt";
                    outputFile = new File("D:/ztest/" + "" + filename);
                    fileWriter = new FileWriter(outputFile);
                }
                fileWriter.append(row + "\r\n");
                rownum++;
            }
            fileWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取文件总行数。
    public static int getTotalLines(String fileName) throws IOException {

        FileReader in = new FileReader(fileName);
        LineNumberReader reader = new LineNumberReader(in);
        String s = reader.readLine();
        int lines = 0;
        while (s != null) {
            lines++;
            s = reader.readLine();
        }
        reader.close();
        in.close();
        return lines;
    }

    public static void main(String[] args) {
        ReadData("D:/test.txt", 3);
    }
}
